<?php
namespace app\http\middleware;
use app\admin\model\system\Node;
use app\common\constants\AdminConstant;
use \liliuwei\think\Auth;
use think\Db;
use think\Loader;
use traits\controller\Jump;

/**
 * 权限处理
 * Class AccessMiddeware
 * @package app\http\middleware
 */
class CheckAuthMiddeware
{
    use Jump;
    public function handle($request, \Closure $next)
    {

        /**
         * 检测登陆
         */
        if (!get_user())
        {
            //$this->error("登录凭证失效请重新登录",'admin/login/index');
            $this->redirect(url("admin/login/index"));
        }

        /**
         * 超级管理员
         */
        if(get_user("id") == AdminConstant::SUPER_ADMIN_ID)  return $next($request);

        /**
         * 请求 url_path
         */
        $httpUrl = strtolower(str_replace("\\","/",get_module().DIRECTORY_SEPARATOR.Loader::parseName(get_controller()).DIRECTORY_SEPARATOR.get_action()));

        /**
         * 排除不需要验证得模块
         */
        $not_check_default = Node::where("auth",0)->cache(true,5)->column('name');


        if(in_array($httpUrl,$not_check_default))  return $next($request);
        /**
         * auth 权限检测
         */
        $auth = new Auth();

        if(!$auth->check($httpUrl,get_user("id")))
        {
            $this->error("权限不足");
        }

        return $next($request);

    }
}
